package base.thread;

import java.util.concurrent.TimeUnit;

/**
 * 什么情况会关闭当前的线程
 *
 * 两种情况
 * 1、进入阻塞状态、在捕获异常中做处理
 * 2、进入运行状态，某个实际被标记为需要中断
 *
 * Author: shen qi han
 * Date: 2022/4/7 下午6:01
 */
public class ThreadExceptionMain {


    public void interruptMethod(){
        Thread t1 = new Thread(() -> {
            while(true){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("被中断，退出....");
                    break;
                }
                System.out.println("thread1 doing....");
            }
        });

        t1.start();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // interrupt the thread 1
        t1.interrupt();
    }

    public void ioMethod(){
        Thread t1 = new Thread(() -> {
            try {
                // 外层中断了，导致里面的状态。还处于阻塞状态，需要推出阻塞状态，然后抛出异常
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
    }

    public static void main(String[] args) {
        ThreadExceptionMain main = new ThreadExceptionMain();
//        main.interruptMethod();
        main.ioMethod();
    }

}
